<?php

function cforge_custom_profile_alter_inc(&$account) {
  $currency = array_shift(currencies_load());
  //add the users balances to the default profile page
  $account->content['balances'] = array (
    '#type' => 'user_profile_item', //this points directly to a tpl.php
    '#title' => t('Balance'),
    '#value' => show_balances($account, array_keys(currencies_load()))
  );

  //add the users balances to the default profile page
  $account->content['balance_history'] = array (
    '#type' => 'user_profile_item', //this points directly to a tpl.php
    '#title' => t('Balance history'),
    '#value' => show_balance_history($account, array($currency->nid), $extent = 'limits', $since = 0)
  );

  $account->content['balance_ometer'] = array (
    '#type' => 'user_profile_item',
    '#title' => t('Balance limits'),
    '#value' => show_balance_ometer($account, $currency->nid)
  );
  $picture_file = $account->picture
    ? $account->picture
    : path_to_theme() . '/anonymous.jpg';

  $account->content['user_picture'] = array(
    '#type' => 'user_profile_item',
    '#value' => theme('imagecache', 'user_image_large', $picture_file),
  );

  $summary[] = $account->profile_responsibility ? '<h4>'.$account->profile_responsibility.'</h4>' : '';
  $summary[] = $account->profile_address ? '<pre>'.$account->profile_address.'</pre>' : '';
  $summary[] = $account->profile_phone1 ? "<strong>tel 1: </strong>$account->profile_phone1" : '';
  $summary[] = $account->profile_phone2 ? "<strong>tel 2: </strong>$account->profile_phone1" : '';

  $account -> content['summary'] = array (
    '#title' => t('Contact'),
    '#type' => 'user_profile_item',
    '#value' => implode("\n<br />", $summary),
  );
}

function cforge_custom_menu_alter_inc(&$items) {
  //rename the /user menu item
  $items['user/%user_uid_optional']['title'] = t('My account');
  //tweak the user tabs
  $items['user/%user/edit']['title'] = t('Account');
  $items['user/%user_uid_optional']['title arguments'][] = $items['user/%user_uid_optional']['title callback'];
  $items['user/%user_uid_optional']['title callback'] = 'cf_user_page_title_wrapper';
  //this is to correct the simplenews callback which has the wrong access
  $items['user/%user_category/edit/newsletter']['access callback'] = 'user_edit_access';
  $items['user/%user_category/edit/newsletter']['access arguments'] = array(1);
  unset($items['user/%user/bureau']);
  $items['user/%views_arg/directory']['weight'] = -1;
  $items['user/%views_arg/acknowledgements']['weight'] = 4;
  $items['user/%user/contact']['weight'] = 5;
  //move some menu items
  $items['image']['menu_name'] = 'secondary-links';
  $items['image']['type'] = MENU_NORMAL_ITEM;
  $items['image']['title'] = t('Gallery');
  $items['contact']['menu_name'] = 'secondary-links';
  $items['contact']['type'] = MENU_NORMAL_ITEM;
  $items['contact']['weight'] = 50;
  $items['admin/mc/unsigned']['menu_name'] = 'manage';

  //these are views-created parent links
  $items['exchanges']['menu_name'] = 'primary-links';
  $items['tasks']['menu_name'] = 'primary-links';
  $items['members']['menu_name'] = 'primary-links';
  //alter the access so the local admin can see some admin pages.
  $items['admin/user/permissions']     ['access arguments'] = array('access administration pages');
  $items['admin/user/roles']		   ['access arguments'] = array('access administration pages');
  $items['admin/user/profile']         ['access arguments'] = array('access administration pages');
  $items['admin/settings/smtp']        ['access arguments'] = array('local admin');
  $items['admin/settings/site-information']         ['access arguments'] = array('local admin');
  $items['admin/build/themes/settings/sky_seldulac']['access callback'] = 'user_access';
  $items['admin/build/themes/settings/sky_seldulac']['access arguments'] = array('local admin');
  $items['admin/mc/notification']                ['access arguments'] = array('local admin');
  //committee can re-arrange menu items but not add and remove them through the menu interface
  $items['admin/build/menu-customize/%menu']     ['access arguments'] = array('committee');
  $items['admin/build/menu/%item/edit']     ['access arguments'] = array('committee');
  $items['admin/build/menu-customize/%menu/list']['access arguments'] = array('committee');
  $items['admin/build/menu-customize/%menu/edit']['access arguments'] = array('committee');
  $items['admin/build/menu-customize/%menu/add'] ['access arguments'] = array('access administration pages');
  $items['admin/build/menu-customize/%menu/delete']['access arguments']=array('access administration pages');
  $items['admin/content/node']                   ['access arguments'] = array('committee');
  $items['admin/content/taxonomy/%taxonomy_vocabulary']['access arguments'] = array('committee');
  $items['admin/content/taxonomy/add/vocabulary']['access arguments'] = array('access administration pages');

  $items['admin/content/image']                  ['access arguments'] = array('committee');
  $items['admin/user/user']                      ['access arguments'] = array('committee');
  $items['admin/user/settings']                  ['access arguments'] =  array('committee');
  $items['logout']['weight'] = 50;
  $items['user/autocomplete']['page callback'] = 'cforge_user_autocomplete';
  $items['user/autocomplete']['access arguments'] = array('exchange');
  $items['user/autocomplete']['file'] = 'cforge_custom.inc';
  $items['user/autocomplete']['file path'] = drupal_get_path('module', 'cforge_custom');
  $items['admin/content/backup_migrate']['page arguments'] = array('', 'backup_migrate_ui_manual_backup_advanced', TRUE);
  $items['admin/content/backup_migrate/export']['page arguments'] = array('', 'backup_migrate_ui_manual_backup_advanced', TRUE);
  unset($items['admin/content/backup_migrate/export/quick']);
  unset($items['admin/content/backup_migrate/export/advanced']);
  if (variable_get('cf_unlaunched', 'not SET') == FALSE) {
    //after launch, override the password reset login function so it doesn't expire after 24 hours
    $items['user/reset/%/%/%']['page arguments'][0] = 'mutual_credit_user_pass_reset';
    $items['user/reset/%/%/%']['file'] = 'cforge_custom.inc';
  }
}

/*
 * hard reset will reset overridden views
 */
function cforge_reset_views($viewname = 'all', $hard = FALSE) {
  $views = views_get_all_views();
  if ($viewname != 'all') {
    $views  = array($viewname => $views[$viewname]);
  }
  $done = array();
  foreach ($views as $viewname => $view) {
    if ($view->tag == 'cforge') {
      if ($view->type != t('Overridden') || $hard) {
        views_object_cache_clear('view', $viewname);
        $view->delete();
        $done[] = $viewname;
      }
    }
  }
  views_invalidate_cache();
  return 'views cached cleared and these views reverted to code: '. implode(', ', $done);
}


/*
 * hard reset deletes all the cforge_custom menu items
 * soft reset just resets certain properties
 */
function cforge_reset_menus($menuname = 'all', $hard = FALSE) {
  global $language;
  $w = 0;
  $def = array('module' => 'cforge_custom', 'hidden' => 0, 'menu_name' => 'setup');
  //These menu titles won't translate if they are different to the item in the router table.
  //That's why most of the are translated here, as they are set up
  //only problem is that the po file hasn't been installed yet.
  $setup[] = $def + array(
    'link_path' => $language->language == 'fr' ? 'http://communityforge.net/fr/setup' : 'http://communityforge.net/setup',
    'link_title' => t('Installation guide'),
    'weight' => $w++,
    'options' => array(
      'attributes' => array(
        'title' => t("Read the official setup documentation on communityforge.net")
      )
    )
  );
  $setup[] = $def + array(
    'link_path' => 'admin/settings/site-information',
    'link_title' => t('Site information'),
    'weight' => $w++,
    'options' => array(
      'attributes' => array(
        'title' => t("Change basic site information, such as the site name, slogan, e-mail address, mission, front page and more.")
      )
    )
  );
  $setup[] = $def + array(
    'link_path' => 'admin/build/themes/settings/sky_seldulac',
    'link_title' => t('Upload Logo'),
    'weight' => $w++,
    'options' => array(
      'attributes' => array(
        'title' => t('Upload the main picture in the top left of the screen')
      )
    )
  );
  $cid = db_result(db_query("SELECT nid from {node} WHERE type = 'currency'"));
  $setup[] = $def + array(
    'link_path' => 'node/'.$cid.'/edit',
    'link_title' => t('Default currency'),
    'weight' => $w++,
    'options' => array(
      'attributes' => array(
        'title' => t("Setup a default currency, exchange and directory settings.")
        )
      )
  );
  $setup[] = $def + array(
    'link_path' => 'admin/user/settings',
    'link_title' => t('Welcome message'),
    'options' => array(
      'attributes' => array(
        'title' => t("Compose the e-mail to be sent on welcoming user.")
      )
    )
  );
  $setup[] = $def + array(
    'link_path' => 'admin/mc/notification',
    'link_title' => t('Mail notifications'),
    'weight' => $w++,
  );
  if (module_exists('smtp')) {
    $setup[] = array(
      'link_path' => 'admin/settings/smtp',
      'link_title' => t('Outgoing mail server'),
      'weight' => $w++,
      'options' => array(
        'attributes' => array(
          'title' => t("Please set to use your own SMTP server")
        )
      )
    );
  }
  $setup[] = $def + array(
    'link_path' => 'admin/build/contact',
    'link_title' => t('Contact form'),
    'weight' => $w++,
    'options' => array(
      'attributes' => array(
        'title' => t("Setup up site wide & member contacts.")
      )
    )
  );
  $setup[] = $def + array(
    'link_path' => 'admin/content/taxonomy',
    'link_title' => t('categories'),
    'weight' => $w++,
  );
  $setup[] = $def + array(
    'link_path' => 'admin/settings/ow',
    'link_title' => $language->language == 'fr' ? "système d'annonces" : t('Offers and wants'),
    'weight' => $w++,
    'options' => array(
      'attributes' => array(
        'title' => t("Determine the complexity of your marketplace")
      )
    )
  );
  //now do the manage menu
  $def['menu_name'] = 'manage';

  $manage[] = $def + array(
    'link_path' => 'admin/content/node',
    'link_title' => 'content',
    'weight' => $w++,
    'options' => array(
      'attributes' => array(
        'title' => t("Manage the contents of a page")
      )
    ),
  );
  $manage[] = $def + array(
    'link_path' => 'admin/user/user',
    'link_title' => t('User management'),
    'weight' => $w++,
    'options' => array(
      'attributes' => array(
        'title' => t("List, add and modify users")
      )
    ),
  );
  $manage[] = $def + array(
    'link_path' => 'admin/build/menu-customize/visitors',
    'link_title' => t('Visitor menu'),
    'weight' => $w++,
    'options' => array(
      'attributes' => array(
        'title' => t("Manage contents of the menu for anonymous users.")
      )
    ),
  );
  $manage[] = $def + array(
    'link_path' => 'admin/build/menu-customize/primary-links',
    'link_title' => t('Major menu'),
    'weight' => $w++,
    'options' => array(
      'attributes' => array(
        'title' => t("Manage the primary members menu, organising offers, wants, etc.")
      )
    ),
  );
  $manage[] = $def + array(
    'link_path' => 'admin/build/menu-customize/secondary-links',
    'link_title' => t('Minor menu'),
    'weight' => $w++,
    'options' => array(
      'attributes' => array(
        'title' => t("Manage secondary member options, contact, galleries, etc.")
      )
    ),
  );
  $manage[] = $def + array(
    'link_path' => 'admin/content/simplenews',
    'link_title' => t('Newsletter content'),
    'weight' => $w++,
    'options' => array(
      'attributes' => array(
        'title' => t("Manage newsletter content, subscriptions, etc.")
      )
    )
  );
  $manage[] = $def + array(
    'link_path' => 'admin/content/backup_migrate',
    'link_title' => t('Backup & Migrate'),
    'weight' => $w++,
  );

  $def['menu_name'] = 'navigation';
  $navigation[] = $def + array(
    'link_path' => 'node/add/proposition',//to make it appear under user
    'link_title' => $language->language == 'fr' ? 'Ajouter une offre/demande' : t('Add offer/want'),
    'weight' => 1,//this puts it right under 'My account'
    'plid' => 0
  );
  if ($menuname != 'all') $cforge_menu_items = $$menuname;
  else $cforge_menu_items = array_merge($setup, $manage, $navigation);
  if (empty($cforge_menu_items)) return 'no menu items in that menu';
  if ($hard) {
    //this first one corrects a problem with installation
    db_query("UPDATE {menu_links} SET router_path =  'admin/build/contact' WHERE menu_name = 'setup' and link_path = 'admin/build/contact'");
    db_query("REPLACE INTO {menu_custom} (menu_name, title) VALUES ('setup', '%s'), ('manage', '%s'), ('visitors', '%s')",
      array(
        ':setup' => t('Setup'),
        ':manage' => t('Manage'),
        ':visitors' => t('Visitors'),
      )
    );
    if ($menuname == 'all') {
      db_query("DELETE FROM {menu_links} WHERE module = 'cforge_custom'");
    }
    else {
      db_query("DELETE FROM {menu_links} WHERE menu_name = '$menuname' AND module = 'cforge_custom'");
    }
  }
  else {
    //add the existing mlids to the previous so it's more of an update than a hard reset
    $result = db_query("SELECT link_path, mlid FROM {menu_links} WHERE module = 'cforge_custom'");
    while ($link = db_fetch_object($result)) {
      $mlids[$link->link_path] = $link->mlid;
    }
    foreach ($cforge_menu_items as $key => $item) {
      if ($mlid = $mlids[$item['link_path']]){
        $cforge_menu_items[$key]['mlid'] = $mlid;
      }
    }
  }
  foreach ($cforge_menu_items as $item)  {
    menu_link_save($item);
  }
  return 'menu reset';
}

/*
 * hard reset does nothing
 */
function cforge_reset_permissions($rid = 'all', $hard = FALSE) {
  if ($hard) {
    db_query('DELETE FROM `permission` WHERE rid <= 7');
  }
  $perms = array(
    DRUPAL_ANONYMOUS_RID => 'access site-wide contact form, view original images, view imagecache user_image_default, view imagecache user_image_large, search content, access content, view propositions, access comments, view non-private documents',
    DRUPAL_AUTHENTICATED_RID => 'view tasks, access site-wide contact form, view original images, view imagecache user_image_default, view imagecache user_image_large, view directory, view exchange stats, access content, search content, subscribe to newsletters, view uploaded files, access user profiles, view propositions, access comments, view private documents',
    RID_TRADER => 'post comments without approval, post comments, commit to tasks, view all balances, create offer, create want, exchange, view all exchanges, post propositions',
    RID_COMMITTEE => 'committee, edit tasks, attach images, administer image galleries, edit directory, create 3rdparty exchanges, administer menu, administer nodes, create event content, create page content, create simplenews content, create story content, create url aliases, administer role expire, administer newsletters, send newsletter, administer simplenews subscriptions, administer taxonomy, upload files, administer permissions, administer users, import users, administer comments, edit documents',
    RID_ACCOUNTANT => 'edit all exchanges, create 3rdparty exchanges',
    RID_LOCAL_ADMIN => 'access backup and migrate, perform backup, local admin, administer site-wide contact form, delete any images, edit any images, translate interface, configure currencies, edit all exchanges, delete any event content, delete any page content, delete any simplenews content, delete any story content, edit any event content, edit any page content, edit any simplenews content, edit any story content, administer actions, administer smtp module, use on-page translation',
    RID_SYSTEM => 'exchange'
  );
  if ($rid != 'all') $perms = array($rid => $perms[$rid]);
  foreach ($perms as $rid => $perm) {
    db_query("REPLACE INTO permission (rid, perm) VALUES (%d, '%s')", $rid, $perm);
  }
  return 'permissions reset for roles: '.implode(',', array_keys($perms));
}


function cforge_reset_blocks($region_name = 'all', $hard = FALSE) {
  global $conf;
  _block_rehash();
  if ($hard) {
    db_query("DELETE FROM {blocks} WHERE theme = '%s'", $conf['theme_default']);
    db_query("REPLACE INTO {blocks_roles} (`module`, `delta`, `rid`) VALUES
      ('user', '0', 1),
      ('menu', 'manage', 4),
      ('menu', 'manage', 6),
      ('block', '6', 6),
      ('block', '7', 6),
      ('menu', 'local-administration', 6),
      ('menu', 'setup', 6),
      ('mc_stats', 'mc_stat_summary', 2),
      ('views', 'member_list-block_1', 1),
      ('user', '1', 2),
      ('views', 'pending_exchanges-block_1', 3),
      ('views', 'pending_exchanges-block_2', 3),
      ('views', 'pending_exchanges-block_3', 3)
    ");
  }
  $regions = array(
    'contenttop' => array(
      array('search', '0', 0, '', '<none>', -1),
      array('menu', 'secondary-links', 0, '', '<none>', -1),
    ),
    'right' => array(
      array('user', '0', 0, '', '', -1),
      array('views', 'mc_exchanges_pending-block_1', 0, '', '', -1),
      array('user', '1', 0, '', '', -1),
      array('user', '1', 0, '', '', -1),
      array('user', '0', 1, 'home', '', -1),
      array('user', '0', 0, '', '', -1),
      array('menu', 'setup', 0, '', '', -1),
      array('menu', 'manage', 0, '', '', -1),
      array('image', '1', 1, 'home\nshare\nstart\ncommit\nnews/recent\ndocs\nlets\ncontacts\nmembers\nrequests\nacknowledgements', 'La vie au SEL', 1),
      array('views', 'comments_recent-block', 0, '', '', -1),
    ),
    'left' => array(
      array('offers_wants', 'propositions_taxonomy_block', 1, 'offers*\nwants*\nnode/add/offer\nnode/add/want', '', 4),
      array('cforge_custom', 'jumpdown', 1, 'faq\n\ndocs\nimage\nlets', '', 4),
      array('views', 'calendar-block_1', 1, 'home\nnews/recent\nnode/add\nimage/\ndocs\ncommit\ncalendar', '', -1),
      array('block', '1', 1, 'home\nLETS\ncommit', '', -1),
      array('mc_webform_1stparty', 'start_exchange', 1, 'user*\nexchanges\nmembers*', '', 1),
      array('offers_wants', 'add_proposition', 1, 'offers*\nwants*', '', 4),
      array('user', '2', 1, 'home\nnews/recent\nmembers', '', -1),
      array('views', 'offers-latest', 1, 'exchanges\ndirectory/offers/*', '', -1),
      array('views', 'wants-latest', 1, 'exchanges\ndirectory/wants/*', '', -1),
      array('views', 'recent_news-block_1', 0, '', '', -1),
    ),
    'contentbottom' => array(
      array('views', 'mc_exchanges_pending-block_2', 1, 'user*', '', -1),
      array('views', 'mc_exchanges_pending-block_3', 1, 'user*', '', -1)
    )
  );
  if ($region_name != 'all') {
    $regions = array($region_name => $regions[$region_name]);
  }
  foreach ($regions as $region_name => $region) {
    $rows = array();
    $w = 0;
    foreach ($region as $block) {
      $w++;
      $rows[] = "('". implode("', '", $block) . "', 1, 0, 0, 'sky_seldulac', '$region_name', '$w')";
    }
    db_query("REPLACE INTO {blocks} (module, delta, visibility, pages, title, cache, status, custom, throttle, theme, region, weight)
      VALUES ". implode(',', $rows)
    );
  }
  
  //video block
  $videoblock = '<object width="275" height="165">
  <param name="movie" value="http://www.youtube.com/v/fwy2sojt3ZM?fs=1&amp;hl=fr_FR"></param><param name="allowFullScreen" value="true"></param>
  <param name="allowscriptaccess" value="always"></param>
  <embed src="http://www.youtube.com/v/fwy2sojt3ZM?fs=1&amp;hl=fr_FR" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="275" height="165"></embed>
</object>';
  //boxes table is for handwritten blocks
  db_query("REPLACE INTO boxes (bid, body, info, format) VALUES (1, '%s', 'video', 2)", $videoblock);
  return 'blocks reset for region: '.implode(',', array_keys($regions));
}

/*
 * hard reset does nothing
 * this needs reworking because it's not a good idea to keep the whole site's strings in one file.
 */
function cforge_reset_translations($lang = 'en', $hard = FALSE) {
  global $language;
  if ($language->language == 'en') return;
  include_once('includes/locale.inc');
  $files = array(
    array('filepath' => 'profiles/cforge/translations/'.$language->language.'.po'),
    array('filepath' => drupal_get_path('module', 'offers_wants') .'/translations/offers_wants.'.$language->language.'.po'),
  );
  foreach ($files as $file) {
    _locale_import_po((object)$file, 'fr', LOCALE_IMPORT_OVERWRITE, 'default');
  }
  return 'translation strings reimported reset';
}

function cforge_dump() {
  $db = $_SERVER['db_name'];
  $pswd = $_SERVER['db_passwd'];
  echo system("mysqldump --user root --password=$pswd $db");
}

//these is used with nodeapi to prepare the page and the dropdownlinks for the block 'jumpdown'
function _get_headings() {
  global $return;
  if (stripos($return, '<h3')) {
    preg_match_all('/<h3>([^<]*)/', $return, $matches);
  }
  else {
  	  preg_match_all('/<caption>([^<]*)/', $return, $matches);
  }
  if (count($matches[1]) < 2 ) return;
  foreach($matches[1] as $match) {
    unset($link);
    //Use only the first three words
    $link =strtok($match, ' ');
    for ($i = 0; $i < 3; $i++){
      $link .= ' '.strtok(' ');
    }
    $block .= "\n<li class=\"leaf\"><a href=\"#$match\">$link</a></li>";
  }
  if ($block) return '<ul>'.$block .'</ul>';
}


function cforge_user_autocomplete($string = '') {
  $matches = array();
  if ($string) {
    $result = db_query(
      "SELECT DISTINCT u.uid, u.name FROM {users} u
      LEFT JOIN {profile_fields} f1 ON f1.name = 'profile_firstname'
      LEFT JOIN {profile_values} v1 ON u.uid = v1.uid AND f1.fid = v1.fid
      LEFT JOIN {profile_fields} f2 ON f2.name = 'profile_familyname'
      LEFT JOIN {profile_values} v2 ON u.uid = v2.uid AND f2.fid = v2.fid
      LEFT JOIN {users_roles} ur ON u.uid = ur.uid
      WHERE u.status = 1 AND u.uid > 0 AND rid = ".RID_TRADER." AND (
        LOWER(u.name) LIKE LOWER('%s%%')
        OR LOWER(u.mail) LIKE LOWER('%s%%')
        OR u.uid LIKE ('%s%%')
        OR LOWER(v1.value) LIKE LOWER('%s%%')
        OR LOWER(v2.value) LIKE LOWER('%s%%')
      )",
      array(':name' => $string, ':email' => $string, ':uid' => $string, ':value1' => $string, ':value' => $string, )
    );
    $traders = get_trader_list();
    while ($user = db_fetch_object($result)) {
      $matches[$user->name] = $traders[$user->uid];
    }
  }
  drupal_json(array_splice($matches, 0, 10));
}

/*
 * Launch sequence
 */
//menu_callback drupal_get_form argument: provide a checklist and lauch button
function cforge_launch($form_state) {
  $def = variable_get('cf_welcome', NULL) ? variable_get('cf_welcome', NULL) : t("Hello !username,
We have launched our new site!
You can now add your offers and wants, and record your transactions on the website.
Don't worry, it's easy and fun, and you can't break anything, so go ahead and have a go.
Once you've logged in with the link below, please change your password. And while you're at it, check your personal details and save your profile page.
Have a nice visit, we'll see you on the site.
!site Team") . "
=======================
";

  $form['cf_welcome'] = array(
    '#title' => t('Welcome message'),
    '#description' => t("This text will be injected at the top of the !mail reminder", array('!mail' => l(t('Password recovery email'), 'admin/user/settings')) ) .' '.
      t('Available variables are:') . ' !username, !site, !password, !uri, !uri_brief, !mailto, !date, !login_uri, !edit_uri, !login_url.',
    '#type' => 'textarea',
    '#rows' => 10,
    '#default_value' => $def,
  );
  $form['testmail'] = array(
    '#type' => 'fieldset',
    '#title' => t('Test mail'),
    '#description' => t('Send a test mail to yourself. WARNING! This will log you out.'),
    'sendtest' => array(
      '#type' => 'submit',
      '#value' => t('Send test mail'),
      '#submit' => array('cforge_test_launch'),
      '#weight' => 1,
    )
  );
  $form['actions'] = array(
    '#weight' => 10,
    'launch' => array(
      '#type' => 'submit',
      '#value' => t('LAUNCH NOW!'),
      '#submit' => array('cforge_launch_now'),
      '#weight' => 1,
    ),
    'dontlaunch' => array(
      '#type' => 'submit',
      '#value' => t('Never launch'),
      '#submit' => array('cforge_launch_disable'),
      '#weight' => 2,
    )
  );
  return $form;
}

function cforge_test_launch($form, $form_state) {
  variable_set('cf_welcome', $form_state['values']['cf_welcome']);
  cf_welcome_send($GLOBALS['user']->uid);
  drupal_set_message(t('Notified @mail', array('@mail' => $GLOBALS['user']->mail)));
  module_load_include('pages.inc', 'user');
  user_logout();
}
function cforge_launch_now($form, $form_state) {
  variable_set('cf_welcome', $form_state['values']['cf_welcome']);
  $traders = cache_get('mc_trader_list');
  foreach(array_keys($traders->data) as $uid){
    cf_welcome_send($uid);
  }
  variable_del('cf_unlaunched', FALSE);
  cforge_launch_disable();
}
function cforge_launch_disable() {
  variable_del('cf_welcome');
  variable_set('cf_unlaunched', FALSE);
  cforge_reset('modules');
  drupal_goto('home');
}

function cf_welcome_send($uid){
  $template = $injection + variable_get('user_mail_password_reset_notify', $default_notify);
  $params['account'] = user_load($uid);
  //cf isn't a module but it's only used to call the wrapper function below
  $mail = drupal_mail('cf', 'password_reset', $params['account']->mail, user_preferred_language($params['account']), $params);
  empty($mail) ?
    drupal_set_message(t('Failed to mail @mail', array('@mail' => $params['account']->mail)), 'warning') :
    drupal_set_message(t('Notified @mail', array('@mail' => $params['account']->mail)));
}
//wrapper function to inject the mail ahead of the body
function cf_mail($key, &$message, $params) {
  $variables = user_mail_tokens($params['account'], $message['language']);
  $message['subject'] = t('Site launch:') .' ';
  $message['body'][] = strtr(variable_get('cf_welcome', NULL), $variables);
  user_mail('password_reset', $message, $params);
}

/*
 * Menu (alter) callback; process one time login link and redirects to the user page on success.
 * this is identical to user_pass_reset, except it doesn't check for expiry
 */
function mutual_credit_user_pass_reset(&$form_state, $uid, $timestamp, $hashed_pass, $action = NULL) {
  module_load_include('pages.inc', 'user');
  global $user;

  // Check if the user is already logged in. The back button is often the culprit here.
  if ($user->uid) {
    drupal_set_message(t('You have already used this one-time login link. It is not necessary to use this link to login anymore. You are already logged in.'));
    drupal_goto();
  }
  else {
    // Time out, in seconds, until login URL expires. 24 hours = 86400 seconds.
    $timeout = 86400;
    $current = time();
    // Some redundant checks for extra security ?
    if ($timestamp < $current && $account = user_load(array('uid' => $uid, 'status' => 1)) ) {
      // Deny one-time login to blocked accounts.
      if (drupal_is_denied('user', $account->name) || drupal_is_denied('mail', $account->mail)) {
        drupal_set_message(t('You have tried to use a one-time login for an account which has been blocked.'), 'error');
        drupal_goto();
      }

      if ($account->uid && $hashed_pass == user_pass_rehash($account->pass, $timestamp, $account->login)) {
        // First stage is a confirmation form, then login
        if ($action == 'login') {
          watchdog('user', 'User %name used one-time login link at time %timestamp.', array('%name' => $account->name, '%timestamp' => $timestamp));
          // Set the new user.
          $user = $account;
          // user_authenticate_finalize() also updates the login timestamp of the
          // user, which invalidates further use of the one-time login link.
          user_authenticate_finalize($form_state['values']);
          drupal_set_message(t('You have just used your one-time login link. It is no longer necessary to use this link to login. Please change your password.'));
          drupal_goto('user/'. $user->uid .'/edit');
        }
        else {
          $form['message'] = array('#value' => t('<p>This is a one-time login for %user_name and will expire on %expiration_date.</p><p>Click on this button to login to the site and change your password.</p>', array('%user_name' => $account->name, '%expiration_date' => format_date($timestamp + $timeout))));
          $form['help'] = array('#value' => '<p>'. t('This login can be used only once.') .'</p>');
          $form['submit'] = array('#type' => 'submit', '#value' => t('Log in'));
          $form['#action'] = url("user/reset/$uid/$timestamp/$hashed_pass/login");
          return $form;
        }
      }
      else {
        drupal_set_message(t('You have tried to use a one-time login link which has either been used or is no longer valid. Please request a new one using the form below.'));
        drupal_goto('user/password');
      }
    }
    else {
      // Deny access, no more clues.
      // Everything will be in the watchdog's URL for the administrator to check.
      drupal_access_denied();
    }
  }
}



/*
 * menu callback drupal_get_form argument
 * not used right now...
 */
function cforge_connect_form() {
  $form['cforge_report'] = array(
    '#type' => 'checkbox',
    '#title' => t('Report our site data to Community Forge.'),
    '#default_value' => variable_get('cforge_report', TRUE),
    '#weight' => -5,
    '#description' => t("Be part of a wider network of local currency comunities by sharing a few key pieces of information with us.").' '.
      t("Only this data will be sent: !link", array('!link' => l('cf_summary', 'cf_summary'))).' '.
      t("These stats motivate us and can be used to promote our work. We seek your trust and will not abuse this information.")
  );
  return system_settings_form($form);
}
function cforge_report($dest = '') {
  $data = cforge_get_report();
  if (!$dest) {
    return theme('cforge_report', $data);
  }
}

function cforge_get_report() {
  $def_cur = db_fetch_object(db_query("SELECT nid, title FROM {node} WHERE type = 'currency'"));
  $result = db_query("SELECT uid FROM {users_roles} WHERE rid = %d", RID_SYSTEM);
  $system_accounts[] = 1;
  while ($uid = db_result($result)) {
    $system_accounts[] = $uid;
  }
  $stats['url'] = array(
    'title' => t('Home page'),
    'value' => $GLOBALS['base_url'],
  );

  $system_accounts = implode(',',$system_accounts);
  $stats['traders'] = array(
    'title' => t('Number of traders'),
    'value' => db_result(db_query("SELECT count(u.uid) FROM {users} u LEFT JOIN {users_roles} ur ON u.uid = ur.uid WHERE ur.rid = %d and u.status = 1", RID_TRADER)),
  );
  $query = "SELECT field from {mc_exchanges} e LEFT JOIN {node} n ON e.nid = n.nid WHERE e.state = 0 AND payer_uid NOT IN ($system_accounts) AND payee_uid NOT IN ($system_accounts) AND e.cid = $def_cur->nid AND n.created > %d";
  $transactions = db_query(str_replace('field', 'count(e.nid)', $query), strtotime('-30 days'));
  $volume = db_query(str_replace('field', 'SUM(e.quantity)', $query), strtotime('-1 year'));
  $stats['transactions'] = array(
    'title' => t('Last 30 days transactions'),
    'value' => db_result($transactions)
  );
  $stats['volume'] = array(
    'title' => t('Last 365 days volume'),
    'value' => theme('money', db_result($volume), $def_cur->nid)
  );
  $stats['propositions'] = array(
    'title' => t('Offers and wants showing'),
    'value' => db_result(db_query("SELECT count(nid) FROM {node} WHERE type = 'proposition' AND status = 1 AND uid NOT IN ($system_accounts)"))
  );
  $stats['name'] = array(
    'title' => t('Site name'),
    'value' => variable_get('site_name', 'no name'),
  );
  $theme_settings = variable_get('theme_sky_seldulac_settings', array());
  $stats['logo'] = array(
    'title' => t('Url of logo'),
    'value' => $theme_settings['logo_path']
  );
  $stats['site_mail'] = array(
    'title' => t('Site mail'),
    'value' => variable_get('site_mail', 'no mail')
  );
  $stats['site_slogan'] = array(
    'title' => t('Site slogan'),
    'value' => variable_get('site_slogan', 'no slogan')
  );
  $stats['currency'] = array(
    'title' => t('Name of (first) currency'),
    'value' => $def_cur->title
  );
  $deficit = db_result(db_query('SELECT min(cleared_balance) FROM {mc_cache}'));
  $stats['deficit'] = array(
    'title' => t('Largest negative balance'),
    'value' => theme('money', $deficit, $def_cur->nid)
  );
  //checks that all balances add up to zero
  $sum = db_result(db_query("SELECT sum(cleared_balance) FROM {mc_cache}"));
  $stats['sum_balances'] = array(
    'title' => t('Balances add up to zero'),
    'value' => $sum == 0 ? t('Yes') : t('No')
  );
  if ($uid = variable_get('intertrading_uid', 0)) {
    $intertraded = db_result(db_query("SELECT cleared_balance FROM {mc_cache} WHERE uid = $uid"));
  }
  $stats['balance_of_trade'] = array(
    'title' => t('Largest negative balance'),
    'value' => theme('money', $intertraded, $def_cur->nid)
  );
  $stats['created'] = array(
    'title' => t('Created on'),
    'value' => db_result(db_query('SELECT created FROM {node} ORDER BY created ASC LIMIT 0, 1'))
  );
  $stats['coordinates'] = array(
    'title' => t('Coordinates'),
    'value' => variable_get('cforge_lat', 0) .' | '. variable_get('cforge_lon', 0)
  );
  return $stats;
}
//this could be made prettier
function theme_cforge_report($stats) {
  $stats['created']['value'] = date('d m Y', $stats['created']['value']);
  return theme('table', array(), $stats);
}
